import 'dart:async';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/course/models/course_response.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:edu/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rxdart/rxdart.dart';

class CourseSearchPageLogic extends ChangeNotifier {
  String searchText = '';
  String? searchKey;

  List<CourseBrief> courses = [];
  bool isLoading = false;
  bool isError = false;

  late final focusNode = FocusNode();
  late final textController = TextEditingController();
  late final textSubject = PublishSubject<String>();
  late final StreamSubscription<String> subscription;
  late final ScrollController scrollController;

  // 参数
  int? _lastPage;
  int _page = 1;
  int _pageSize = 20;

  CancelToken? _cancelToken;

  List<String>? topCourseKeys;

  bool get isCourseEmpty => courses.isEmpty;
  bool get isSearchTextEmpty => searchText.isEmpty;

  // 是否还有更多数据
  bool get canLoadMore {
    if (_lastPage != null) {
      return _page <= _lastPage!;
    } else {
      return true;
    }
  }

  // 搜索历史
  List<String> searchHistories = [];
  bool get isSearchHistoryEmpty => searchHistories.isEmpty;

  CourseSearchPageLogic();

  void init() {
    scrollController = ScrollController();
    scrollController.addListener(() {
      // 滚动到底部时加载更多数据
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        if (canLoadMore) {
          search();
        }
      }
    });

    textController.addListener(() {
      textSubject.add(textController.text);
    });

    subscription = textSubject.stream
        .sampleTime(Duration(milliseconds: 1000))
        .listen((text) {
          _setSearchText(text: text, key: text.trim());
        });

    DatabaseHelper.shared.getSearchHistories().then((value) {
      searchHistories = value;
      notifyListeners();
    });

    // 延迟加载,防止同时出发notifyListeners()的监听
    Future.delayed(Duration.zero, () {
      loadTopCourseKeys();
    });
  }

  // 清空搜索框
  void clearSearchText() {
    textController.text = '';
    _setSearchText(text: '', key: '');
    focusNode.requestFocus();
  }

  // 更新搜索框内容
  void updateSearchText(String text) {
    focusNode.unfocus();
    textController.text = text;
    _setSearchText(text: text, key: text.trim());
    insertSearchText(text);
  }

  void clearSearchHistories() {
    DatabaseHelper.shared.clearSearchHistories().then((value) {
      searchHistories.clear();
      notifyListeners();
    });
  }

  // 插入搜索框内容
  void insertSearchText(String text) async {
    await DatabaseHelper.shared.insertSearchText(text.trim());
    searchHistories = await DatabaseHelper.shared.getSearchHistories();
    notifyListeners();
  }

  // 设置搜索框内容
  void _setSearchText({required String text, required String key}) {
    if (text == searchText) {
      return;
    }

    searchText = text;
    if (key.isEmpty) {
      courses.clear();
      notifyListeners();
    }

    if (isLoading && _cancelToken != null) {
      _cancelToken?.cancel('new search');
      _cancelToken = null;
      isLoading = false;
    }

    _page = 1;
    searchKey = key;
    if (searchKey != null && searchKey!.isNotEmpty) {
      search();
    }
  }

  @override
  void dispose() {
    textSubject.close();
    _cancelToken?.cancel();
    subscription.cancel();
    scrollController.dispose();
    super.dispose();
  }

  // 获取热门课程top
  Future<void> loadTopCourseKeys() async {
    try {
      final response = await DataFetcher.shared.courseApi.getTopCourseKeys();
      if (response.code == 0 && response.keys != null) {
        topCourseKeys = response.keys;
        notifyListeners();
      } else if (response.code != 0) {
        topCourseKeys = null;
      }
    } catch (e) {
      topCourseKeys = null;
    }
  }

  // 搜索, 调用后端接口
  Future<void> search({String? key}) async {
    final keyword = key ?? searchKey;
    if (keyword == null || keyword.isEmpty) {
      return;
    }

    try {
      if (isLoading) {
        return;
      }
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: true,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      _cancelToken ??= CancelToken();
      final response = await DataFetcher.shared.courseApi.searchCoursesByKey(
        key: keyword,
        page: _page,
        pageSize: _pageSize,
        cancelToken: _cancelToken,
      );
      isLoading = false;
      EasyLoading.dismiss();

      if (response.code == 0 && response.courses != null) {
        if (_page == 1) {
          courses.clear();
        }
        courses.addAll(response.courses!);
        _lastPage = response.pageMeta?.lastPage;
        _pageSize = response.pageMeta?.pageSize ?? 20;
        _page = (response.pageMeta?.currentPage ?? _page) + 1;
      } else {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.searchCourseError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      isLoading = false;
      isError = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
    } catch (e) {
      log('Error: $e');
    } finally {
      _cancelToken?.cancel();
      _cancelToken = null;
    }
  }
}
